<?php
class CiuexamCiuusersController extends AppController {

	var $name = 'CiuexamCiuusers';
	
	var $components = array('Session');

	function index() {
		$this->CiuexamCiuuser->recursive = 0;
		$this->set('ciuexamCiuusers', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid ciuexam ciuuser', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('ciuexamCiuuser', $this->CiuexamCiuuser->read(null, $id));
	}

      function add($exam=Null , $plan=Null, $period=Null) {       
           
         $this->CiuexamCiuuser->create();     
         $data=$this->data;
         $documento=$data['CiuexamCiuuser']['document'] ;
         $raw=$this->CiuexamCiuuser->Ciuuser->findByDocument($documento);
         $data['CiuexamCiuuser']['ciuuser_id'] = $raw['Ciuuser']['id'];
         $data['CiuexamCiuuser']['ciuadmisionstate_id'] = 2;
         if (!empty($this->data)) { 
             if($data['CiuexamCiuuser']['document'] >0){
                  $existe = $this->CiuexamCiuuser->Ciuuser->existeestudiante($documento);
                  if($existe ){   // valida si existe el documento  
                       $sql="select examuser.id 
                             from ciuexam_ciuusers examuser
                             join ciuexams exam on examuser.ciuexam_id=exam.id
                             join ciuplans plan on exam.ciuplan_id = plan.id
                             where examuser.ciuuser_id = ".$data['CiuexamCiuuser']['ciuuser_id'].
                              " and exam.ciuacademicperiod_id= ".$data['CiuexamCiuuser']['period'].
                              "  and plan.ciulanguage_id = ". $data['CiuexamCiuuser']['plan']
                           ;
                        $ejecutasql=$this->CiuexamCiuuser->query($sql);
                        $examusers = array();
                        foreach ($ejecutasql as $key => $val) {
                             $examusers[] = $val['examuser']['id'];
                             $this->CiuexamCiuuser->delete($val['examuser']['id']);
                         }
                         $this->CiuexamCiuuser->delete(array('conditions'=>array('CiuexamCiuuser.id'=> $plan) ));
                        if ($this->CiuexamCiuuser->save($data)) {
                            $countPeople="select count(*) as qty from ciuexam_ciuusers where ciuexam_id=" . $data['CiuexamCiuuser']['ciuexam_id'] ;
                            $result=$this->CiuexamCiuuser->query($countPeople);
                            $qty=$result[0][0]['qty'];	
                            if($qty<1){
                             $qty=0;
                            }
                            $update="update ciuexams set people_count='". $qty. "' where id= ".$data['CiuexamCiuuser']['ciuexam_id']; //cambia el numero de personas en el examen 
                            $this->CiuexamCiuuser->query($update);
                                       
                            $this->Session->setFlash(__('Se le asigno examen al estudiante', true));   
                            $this->redirect(array('controller' => 'ciuexams', 'action' => 'view',$data['CiuexamCiuuser']['ciuexam_id']));
                        } else {
                            $this->Session->setFlash(__('The ciuexam ciuuser could not be saved. Please, try again.', true));
                        }
                   }else {
                     $this->Session->setFlash(__('Verifique el documento ingresado', true));
                                        // se borra lo que contenia la vista add
                   }
	       }else {
		  $this->Session->setFlash(__('Document must be numeric', true));
	       }
	   }
           $periods= $this->CiuexamCiuuser->Ciuexam->Ciuacademicperiod->find('list',array('conditions'=>array('Ciuacademicperiod.id'=> $period) ));
           $plans = $this->CiuexamCiuuser->Ciuexam->Ciuplan->find('list',array('conditions'=>array('Ciuplan.id'=> $plan) ));
           $ciuusers = $this->CiuexamCiuuser->Ciuuser->find('list',array('conditions'=>array('Ciuuser.document'=> $documento) ));
           $ciuexams = $this->CiuexamCiuuser->Ciuexam->find('list',array('conditions'=>array('Ciuexam.id'=> $exam) ));
           $this->set(compact('ciuusers', 'ciuexams','plans','periods'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid ciuexam ciuuser', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->CiuexamCiuuser->save($this->data)) {
				$this->Session->setFlash(__('The ciuexam ciuuser has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The ciuexam ciuuser could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->CiuexamCiuuser->read(null, $id);
		}
		$ciuusers = $this->CiuexamCiuuser->Ciuuser->find('list');
		$ciuexams = $this->CiuexamCiuuser->Ciuexam->find('list');
		$this->set(compact('ciuusers', 'ciuexams'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for ciuexam ciuuser', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->CiuexamCiuuser->delete($id)) {
			$this->Session->setFlash(__('Ciuexam ciuuser deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Ciuexam ciuuser was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	function grade($id = null) {
		$exam_id=0;
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid ciuexam ciuuser', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->CiuexamCiuuser->save($this->data)) {	    
		        $exam_id=$this->data['CiuexamCiuuser']['ciuexam_id'];
				$this->Session->setFlash(__('The ciuexam ciuuser has been saved', true));
				$this->redirect(array('controller'=>'ciuexams','action' => 'view', $exam_id));
			} else {
				$this->Session->setFlash(__('The ciuexam ciuuser could not be saved. Please, try again.', true));
			}
		}
		$exam_id=0;
		$plan_id=0;
		$user_id=0;
		if (empty($this->data)) {
			$this->data = $this->CiuexamCiuuser->read(null, $id);
			$exam_id = $this->data['CiuexamCiuuser']['ciuexam_id'];
			$plan_id = $this->data['Ciuexam']['ciuplan_id'];
			$user_id = $this->data['CiuexamCiuuser']['ciuuser_id'];
		}
		$ciuexams = $this->CiuexamCiuuser->Ciuexam->find('list',array('conditions'=>array('Ciuexam.id'=> $exam_id)));
		$ciuusers = $this->CiuexamCiuuser->Ciuuser->find('list',array('conditions'=>array('Ciuuser.id'=> $user_id) ));
        $ciusubjects = $this->CiuexamCiuuser->Ciuexam->Ciuplan->Ciusubject->find('list',array('conditions'=>array('Ciusubject.ciuplan_id'=> $plan_id)));
        $this->set(compact('ciuusers', 'ciuexams', 'ciusubjects'));
	}
	    
    public function load() {
	$salida='';
        $this->set('salida',$salida);
        $archivo=array();
        $this->CiuexamCiuuser->create();
        if (!empty($this->data)) {     
            if( $this->data['CiuexamCiuuser']['archivo']['error'] == 0 &&  $this->data['CiuexamCiuuser']['archivo']['size'] > 0){
                  $archivo=$this->data;
                  $archivo=$archivo['CiuexamCiuuser']['archivo'];
                  $destino = TMP . 'uploads'.DS;
                  if(move_uploaded_file($archivo['tmp_name'], $destino.$archivo['name'])){               
                        $salida=$this->import($archivo['name']);       
                        $this->Session->setFlash(__('Proceso finalizado',true));
                        $this->set('salida',$salida['messages']);
                  }
                  else{
                        $this->Session->setFlash(__('El archivo no se pudo subir, por favor intentelo de nuevo',true));       
                  }
            }else{
                  $this->Session->setFlash(__('Error al intentar subir el archivo'));
            }
        }
    }
    
    function import($filename) {
        // to avoid having to tweak the contents of
        // $data you should use your db field name as the heading name
        // eg: CiuexamCiuusers.id, CiuexamCiuusers.title, CiuexamCiuusers.description
        
        // set the filename to read CSV from
        $filename = TMP . 'uploads' . DS . $filename;
         
        $handle = fopen($filename, "r");
        $header = fgetcsv($handle);
         
        // create a message container
        $return = array(
            'messages' => array(),
        );

        $i=0;
        // read each data row in the file
        while (($row = fgetcsv($handle)) !== FALSE) {
            $i++;
            $flag = true;
            $data = array();
            foreach ($header as $k=>$head) {
                $data['ciuexam_ciuusers'][$head]=(isset($row[$k])) ? $row[$k] : '';
            }

            //$this->CiuexamCiuuser->create();
            // validar que el idioma del examen sea el mismo de la asignatura
            $userData = $this->CiuexamCiuuser->Ciuuser->findByDocument($data['ciuexam_ciuusers']['documento']);
            $dataStorage['ciuuser_id']    = $userData['Ciuuser']['id'];
            $dataStorage['ciuexam_id']    = $data['ciuexam_ciuusers']['id_examen'];
            $dataStorage['grade']         = $data['ciuexam_ciuusers']['calificacion'];
            $dataStorage['ciusubject_id'] = $data['ciuexam_ciuusers']['asignatura'];

            $id = $this->CiuexamCiuuser->find('first',array('conditions'=>array('ciuuser_id'=>$dataStorage['ciuuser_id'],'ciuexam_id'=>$dataStorage['ciuexam_id'])
                                                           ,'fields' => array('CiuexamCiuuser.id')));


            if (empty($id)){
                $return['messages'][] = __(sprintf('Reg. %d Error, el numero de documento no esta registrado en el sistema',$i), true);    
                $flag = false;
            }
            
            $dataStorage['id']=$id['CiuexamCiuuser']['id'];
            $ciuexam  = $this->CiuexamCiuuser->Ciuexam->findById($dataStorage['ciuexam_id']); // aca necesito recuperar el plan
            $ciuplan_id1=$ciuexam['Ciuexam']['ciuplan_id'];
            //recupero todos los subjects que estan relacionados con el plan que traje anteriormente
            $ciuplan = $this->CiuexamCiuuser->Ciusubject->find('all',array('conditions'=>array('Ciusubject.ciuplan_id'=>$ciuplan_id1)
                                                                              ,'fields'=>array('Ciusubject.id')));

            $subject_id=array();
            foreach($ciuplan as $key => $row){
                    $subject_id[]=$row['Ciusubject']['id'];
            }

            if (!in_array($dataStorage['ciusubject_id'],$subject_id)){
                $return['messages'][] = __(sprintf('Reg. %d Error, asignatura no coninciden con las asociadas al examen',$i), true);    
                $flag = false;
            }
            if ($flag){
                if (!$this->CiuexamCiuuser->save($dataStorage)) {
                    $return['messages'][] = __(sprintf('Reg. %d Error, no pudo ser guardado el registro',$i), true);
                }else {
                    $return['messages'][] = __(sprintf('Reg. %d Ok, cargado el registro',$i), true);
                    $flag = true;
                }
            }
        }

        fclose($handle);
        return $return; 
    }

}